{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 配对四格表资料的 $ \\chi^2 $ 检验\n",
    "\n",
    "实质是比较两个二项分布影响变量的影响程度是否相同。\n",
    "\n",
    "四格表："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div><style>\n",
       ".dataframe > thead > tr,\n",
       ".dataframe > tbody > tr {\n",
       "  text-align: right;\n",
       "  white-space: pre-wrap;\n",
       "}\n",
       "</style>\n",
       "<small>shape: (2, 3)</small><table border=\"1\" class=\"dataframe\"><thead><tr><th>index</th><th>B+</th><th>B-</th></tr><tr><td>str</td><td>i64</td><td>i64</td></tr></thead><tbody><tr><td>&quot;A+&quot;</td><td>48</td><td>24</td></tr><tr><td>&quot;A-&quot;</td><td>20</td><td>106</td></tr></tbody></table></div>"
      ],
      "text/plain": [
       "shape: (2, 3)\n",
       "┌───────┬─────┬─────┐\n",
       "│ index ┆ B+  ┆ B-  │\n",
       "│ ---   ┆ --- ┆ --- │\n",
       "│ str   ┆ i64 ┆ i64 │\n",
       "╞═══════╪═════╪═════╡\n",
       "│ A+    ┆ 48  ┆ 24  │\n",
       "│ A-    ┆ 20  ┆ 106 │\n",
       "└───────┴─────┴─────┘"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import polars as pl\n",
    "\n",
    "df = pl.read_csv(\"B_09_5-data.csv\")\n",
    "\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "$ b + c = 20 + 24 = 44 > 40 $，使用未校正的 McNemar 检验公式。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "chi square value = 0.36363636363636365\n",
      "p value = 0.5464935954065822\n"
     ]
    }
   ],
   "source": [
    "from statsmodels.stats.contingency_tables import mcnemar\n",
    "\n",
    "table = df.select(\"B+\",\"B-\")\n",
    "\n",
    "res = mcnemar(table, exact=False, correction=False)\n",
    "\n",
    "print(f\"chi square value = {res.statistic}\")\n",
    "print(f\"p value = {res.pvalue}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "P > 0.05, 按照 $ \\alpha = 0.05 $ 水准，不能认为两种培养基的阴性率不同。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
